package com.zdlee.netty.server10.client;

import com.zdlee.netty.server10.command.LoginRequestPacket;
import com.zdlee.netty.server10.command.Packet;
import com.zdlee.netty.server10.command.PacketCodeC;
import com.zdlee.netty.server10.response.LoginResponsePacket;
import com.zdlee.netty.server10.response.MessageResponsePacket;
import com.zdlee.netty.server10.util.LoginUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.UUID;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-11-29 13:52
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(new Date() + ": 客户端开始登录");
        //创建登录对象
        LoginRequestPacket loginRequestPacket=new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUsername("flash");
        loginRequestPacket.setPassword("pwd");

        //编码
        ByteBuf buffer= PacketCodeC.INSTANCE.encode(ctx.alloc(),loginRequestPacket);
        //写数据
        ctx.channel().writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf= (ByteBuf) msg;
        Packet packet= PacketCodeC.INSTANCE.decode(buf);
        if(packet instanceof LoginResponsePacket)
        {
            LoginResponsePacket loginResponsePacket= (LoginResponsePacket) packet;
            if(loginResponsePacket.isSuccess())
            {
                System.out.println(new Date() + ": 客户端登录成功");
                LoginUtil.markAsLogin(ctx.channel());
            }else
            {
                System.out.println(new Date() + ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
            }
        }else if(packet instanceof MessageResponsePacket)
        {
            MessageResponsePacket messageResponsePacket= (MessageResponsePacket) packet;
            System.out.println(new Date()+": 收到服务端的消息: "+ messageResponsePacket.getMessage());
        }

    }
}
